package cn.ges.wechat

import cn.ges.json.JsonUtil
import cn.ges.resttemplate.OutHttpUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File

/**
 * @author gespent@163.com
 * @date 2020/05/18 15:09
 */
class WeChatRequestUtil {


    companion object {
        private val log: Logger = LoggerFactory.getLogger(WeChatRequestUtil::class.java)

        /**
         * 微信提现相关
         */
        fun wxTransfer(url: String, xml: String, wxPayMchid: String, wxCertificatePath: String): String? {
            val file = File(wxCertificatePath)
            if (!file.exists()) {
                log.error("微信提现证书文件不存在,请及时处理")
            }
            return OutHttpUtil.enterprisePayment(url, xml, wxCertificatePath, wxPayMchid)
        }

        /**
         * 获得微信用户AccessToken
         */
        fun getWeChatUserAccessToken(wxAppId: String, wxAppSecret: String, code: String?): AccessToken? {
            val responseEntity = OutHttpUtil.restTemplate.getForEntity(
                    "https://api.weixin.qq.com/sns/oauth2/access_token?appid={1}&secret={2}&code={3}&grant_type=authorization_code",
                    String::class.java, wxAppId, wxAppSecret, code)
            val body = responseEntity.body
            return try {
                val accessToken: AccessToken = JsonUtil.jsonToObject(body, AccessToken::class.java)
                if (accessToken.errcode != null) {
                    null
                } else {
                    accessToken
                }
            } catch (e: Exception) {
                null
            }
        }

        /**
         * 用accessToken获得用户详细信息
         */
        fun getWeChatUserInfo(accessToken: String?, openId: String?): UserInfo? {
            val responseEntity = OutHttpUtil.restTemplate.getForEntity(
                    "https://api.weixin.qq.com/sns/userinfo?access_token={1}&openid={2}",
                    String::class.java, accessToken, openId)
            return try {
                val userInfo = JsonUtil.jsonToObject(responseEntity.body, UserInfo::class.java)
                if (userInfo.errcode != null) {
                    null
                } else {
                    userInfo
                }
            } catch (e: Exception) {
                null
            }
        }


    }
}